package com.lebo.portal.mybatis.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 测试发现, mybatis使用rs.getTimestamp()读取时间时会使用时区,导致获得的时间跟数据中看到的不一致;
 * 所以使用rs.getString()来规避这个问题
 * @author Aaron
 *
 */
public class TimestampHandler extends BaseTypeHandler<Timestamp> {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Timestamp getNullableResult(ResultSet rs, String columnName) throws SQLException {
        if(null != rs.getString(columnName)) {
            return Timestamp.valueOf(rs.getString(columnName));
        }
        return null;
    }

    @Override
    public Timestamp getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        if(null != rs.getString(columnIndex)) {
            return Timestamp.valueOf(rs.getString(columnIndex));
        }
        return null;
    }

    @Override
    public Timestamp getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        if(null != cs.getString(columnIndex)) {
            return Timestamp.valueOf(cs.getString(columnIndex));
        }
        return null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Timestamp parameter, JdbcType jdbcType)
            throws SQLException {
        logger.debug("setNonNullParameter = {}",parameter.toString());
        ps.setString(i, parameter.toString());
    }
}